﻿using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;

using Sunyi.Project.WebPoint.DataContract;

namespace Sunyi.Project.WebPoint.DataAccess
{
    public partial class IssueDao
    {
        public int SearchCount(string issueTitle, string status, string ownerName, string creatorName, bool isActive)
        {
            int count = 0;

            SqlConnection connection = ConnectionProvider.CreateConnection();
            SqlCommand command = connection.CreateCommand();
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "procTR_Issue_Search_Count";
            command.Parameters.Add(new SqlParameter("@IssueTitle", issueTitle));
            command.Parameters.Add(new SqlParameter("@Status", status));
            command.Parameters.Add(new SqlParameter("@OwnerName", ownerName));
            command.Parameters.Add(new SqlParameter("@CreatorName", creatorName));
            command.Parameters.Add(new SqlParameter("@IsActive", isActive));

            try
            {
                connection.Open();

                count = (int)command.ExecuteScalar();
            }
            finally
            {
                ConnectionProvider.CloseConnection(connection);
            }

            return count;
        }

        public Collection<Issue> Search(string issueTitle, string status, string ownerName, string creatorName, bool isActive, int pageIndex, int pageSize)
        {
            Collection<Issue> issues = new Collection<Issue>();

            SqlConnection connection = ConnectionProvider.CreateConnection();
            SqlCommand command = connection.CreateCommand();
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "procTR_Issue_Search";
            command.Parameters.Add(new SqlParameter("@IssueTitle", issueTitle));
            command.Parameters.Add(new SqlParameter("@Status", status));
            command.Parameters.Add(new SqlParameter("@OwnerName", ownerName));
            command.Parameters.Add(new SqlParameter("@CreatorName", creatorName));
            command.Parameters.Add(new SqlParameter("@IsActive", isActive));
            command.Parameters.Add(new SqlParameter("@PageIndex", pageIndex));
            command.Parameters.Add(new SqlParameter("@PageSize", pageSize));

            try
            {
                connection.Open();

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Issue issue = CreateEntityByReader(reader);
                        issues.Add(issue);
                    }
                }
            }
            finally
            {
                ConnectionProvider.CloseConnection(connection);
            }

            return issues;
        }
    }
}
